package com.example.wms_supermarket.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.wms_supermarket.entity.Goods;
import com.example.wms_supermarket.entity.InStockTable;
import com.example.wms_supermarket.entity.Message;
import com.example.wms_supermarket.entity.OutStockTable;
import com.example.wms_supermarket.entity.Record;
import com.example.wms_supermarket.service.OutStockTableService;
import com.example.wms_supermarket.service.impl.GoodServiceImpl;
import com.example.wms_supermarket.service.impl.OutStockTableServiceImpl;
import com.example.wms_supermarket.service.impl.RecordServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@Tag(name = "OutStockController", description = "管理出库的接口")
public class OutStockController {
    @Autowired
    private OutStockTableServiceImpl outStockTableService;
    @Autowired
    private KafkaTemplate<Object, Object> template;
    @Autowired
    private RecordServiceImpl recordService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private GoodServiceImpl goodService;
    @Operation(summary = "获取所有的出库单信息", description = "获取所有的出库单信息")
    @Parameters({
            @Parameter(in = ParameterIn.COOKIE,name = "userId",required = true,description="用户的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "token",required = true,description="用户的登录令牌"),
    })
    @ApiResponse(description = "所有的出库单信息", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Message.class)))
    @GetMapping(path = "/getAllOutTable")
    public void getAllTable(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        Message<List<OutStockTable>> msg = outStockTableService.queryAll(httpServletRequest);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().println(msg.toJson());
    }
    @Operation(summary = "获取某个状态的出库单信息", description = "获取某个状态的出库单信息")
    @Parameters({
            @Parameter(name = "status", required = true,description="要查询的状态，2为待审核，1为出库中，0为已出库"),
            @Parameter(in = ParameterIn.COOKIE,name = "userId",required = true,description="用户的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "token",required = true,description="用户的登录令牌"),
    })
    @ApiResponse(description = "某个状态的出库单信息", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Message.class)))
    @GetMapping(path = "/getOutTableByStatus")
    public void getTableByStatus(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        Message<List<OutStockTable>> msg = outStockTableService.queryByStatus(httpServletRequest);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().println(msg.toJson());
    }
    @Operation(summary = "获取某个id的出库单信息", description = "获取某个id的出库单信息")
    @Parameters({
            @Parameter(name = "tid", required = true,description="出库单的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "userId",required = true,description="用户的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "token",required = true,description="用户的登录令牌"),
    })
    @ApiResponse(description = "某个id的出库单信息", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Message.class)))
    @GetMapping(path = "/getOutTableByTid")
    public void getTableByTid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        Message<OutStockTable> msg = outStockTableService.queryByTid(httpServletRequest);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().println(msg.toJson());
    }
    @Operation(summary = "获取货物为某个id的出库单信息", description = "获取货物为某个id的出库单信息")
    @Parameters({
            @Parameter(name = "gid", required = true,description="出库单中货物的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "userId",required = true,description="用户的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "token",required = true,description="用户的登录令牌"),
    })
    @ApiResponse(description = "货物为某个id的出库单信息", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Message.class)))
    @GetMapping(path = "/getOutTableByGid")
    public void getTableByGid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        Message<List<OutStockTable>> msg = outStockTableService.queryByGid(httpServletRequest);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().println(msg.toJson());
    }
    @Operation(summary = "生成一个出库单", description = "生成一个出货单")
    @Parameters({
            @Parameter(name = "gid", required = true,description="生成的出货单中的货物id"),
            @Parameter(in = ParameterIn.COOKIE,name = "userId",required = true,description="用户的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "token",required = true,description="用户的登录令牌"),
    })
    @ApiResponse(description = "生成出货单的结果", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Message.class)))
    @GetMapping(path = "/insertOutTable")
    public void insertTable(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        Message msg = outStockTableService.insertOutTable(httpServletRequest);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().println(msg.toJson());
    }
    @Operation(summary = "审核某个id的出库单", description = "审核某个id的出库单")
    @Parameters({
            @Parameter(name = "tid", required = true,description="要审核的出库单的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "userId",required = true,description="用户的id"),
            @Parameter(in = ParameterIn.COOKIE,name = "token",required = true,description="用户的登录令牌"),
    })
    @ApiResponse(description = "审核出货单的结果", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Message.class)))
    @GetMapping(path = "/grantOutTable")
    public void grantTable(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        Message msg = outStockTableService.grantOutTable(httpServletRequest);
        Message<OutStockTable> msg1=outStockTableService.queryByTid(httpServletRequest);
        if (msg1.getCode() == 0) {
            System.out.println("发送的信息");
            System.out.println(msg1.toJson());
            template.send("wms_to_shelves_topic_out_stock",msg1.toJson());
        }
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().println(msg.toJson());
    }
    //监听货车情况的监听器
    @KafkaListener(id = "wms_listen_to_truck_out", topics = "truck_to_wms_topic_out_stock")
    public void listen_truck_out(String input) {
        JSONObject jsonObject=JSONObject.parseObject(input);
        String code=jsonObject.getString("code");
        String msg=jsonObject.getString("msg");
        System.out.println(msg);
        if (!code.equals("106")){
            JSONObject data=JSONObject.parseObject(jsonObject.getString("data"));
            String tid=data.getString("tid");
            recordService.insertRecord(new Record(Integer.parseInt(tid),msg, LocalDateTime.now().toString(),"出库"));
            if (code.equals("1")){
                System.out.println("还在出库中");
            }
            else{
                System.out.println("已经出库了");
            }
        }
    }
    //监听货架情况的监听器
    @KafkaListener(id = "wms_listen_to_shelves_out", topics = "shelves_to_wms_topic_out_stock")
    public void listen_shelves_out(String input) {
        JSONObject jsonObject=JSONObject.parseObject(input);
        String code=jsonObject.getString("code");
        String msg=jsonObject.getString("msg");
        System.out.println(msg);

        if (code.equals("107")){
            System.out.println("该货物不存在");
        }
        else{
            JSONObject data=JSONObject.parseObject(jsonObject.getString("data"));
            String tid=data.getString("tid");
            String gid=data.getString("gid");
            String shId=data.getString("shId");
            System.out.println(tid+"订单准备出库了，正在调用方法。。。。。"+gid);
            System.out.println("已经出库了");
            outStockTableService.completeOutTable(Integer.parseInt(tid));
            goodService.deleteGoods(Integer.parseInt(gid));
            try {
                webSocketServer.sendMessageAll(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
